<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{User as Users, Address, IntergralBanner, IntergralCate, IntergralGoods, IntergralOrder, IntergralOrdergoods, Region, Payment, Wechat, Douyin};
use think\Validate;
use think\Db;

class Goods extends Base
{

    public function cate()
    {
        $list = (new IntergralCate())->where('isshow', 1)->order('sort desc')->field('isshow,created,orders', true)->select();
        $this->result($list, 0, '获取成功');
    }

    public function categoods()
    {
        $cate = $this->request->get('cate/d', 0);
        $ishot = $this->request->get('ishot/d', 0);
        $list = (new IntergralGoods())->where('puton', 1);
        if ($cate) {
            $list = $list->where('cateid', $cate);
        }
        if ($ishot) {
            $list = $list->where('ishot', $ishot);
        }
        $list = $list->order(['ishot desc'])->field('isshow,created,detail,puton,cateid', true)
            ->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['images'] = json_decode($lists['images'], true);
        }
        $this->result($list, 0, '获取成功');
    }


    public function goodsdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new IntergralGoods())->where('id', $id)->field('isshow,created,puton,cateid', true)->find();
        if (!empty($list)) {
            $list['images'] = json_decode($list['images'], true);
            $list['detail'] = json_decode($list['detail'], true);
        }
        $this->result($list, 0, '获取成功');
    }

    public function add_order()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'addressid' => 'require',
            'goodsid' => 'require',
            'num' => 'require|gt:0|number'
        ], [
            'addressid.require' => '地址id不能为空',
            'goodsid.require' => '商品id不能为空',
            'num.require' => '商品数量不能为空',
            'num.gt' => '商品数量必须大于0',
            'num.number' => '商品数量必须是整数',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $iorder = (new IntergralOrder())->where(['user_id' => $this->request->user_id, 'status' => 0])->find();
        if (!empty($iorder)) {
            $this->result([], 1, '您有未支付的订单，请先支付或取消订单');
        }
        //判断收货地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址信息不存在');
        }
        $good = (new IntergralGoods())->where('id', $data['goodsid'])->where('puton', 1)->find();
        if (empty($good)) {
            $this->result([], 1, '商品已下架');
        }
        if ($good['sku'] < $data['num']) {
            $this->result([], 1, '商品库存不足');
        }
        $total = $data['num'] * $good['intergral'];
        $money = $data['num'] * $good['price'];
        $user = (new Users())->where(['id' => $this->request->user_id])->find();
        if ($user['integral'] < $total) {
            $this->result([], 1, '积分不足');
        }
        if ($money == 0) {
            $status = 1;
        } else {
            $status = 0;
        }
        $id = 0;
        Db::startTrans();
        try {
            (new IntergralGoods())->where('id', $data['goodsid'])->setDec('sku', $data['num']);
            $id = (new IntergralOrder())->insertGetId([
                'user_id' => $this->request->user_id,
                'name' => $address['name'],
                'mobile' => $address['mobile'],
                'province' => $address['province'],
                'area' => $address['area'],
                'city' => $address['city'],
                'street' =>  $address['street'],
                'address' =>  $address['address'],
                'lon' => $address['lon'],
                'lat' =>  $address['lat'],
                'status' => $status,
                'total' => $total,
                'money' => $money,
                'info' => !empty($data['info']) ? $data['info'] : '',
                'dates' => date('Y-m-d')
            ]);
            (new IntergralOrdergoods())->insert([
                'orderid' => $id,
                'goodsid' => $data['goodsid'],
                'num' => $data['num'],
                'title' => $good['title'],
                'shortitle' => $good['shortitle'],
                'price' => $good['price'],
                'intergral' => $good['intergral'],
                'images' => $good['images']
            ]);
            if ($total > 0) {
                (new Users())->IntergralEdit($user['id'], $user['integral'], -$total, 2, $id, '兑换商品');
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败');
        }
        $this->result(['id' => $id], 0, '操作成功');
    }


    public function order()
    {
        $list = (new IntergralOrder())->order('id desc');
        $status = $this->request->get('status/d', 0);
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->field('id,status,created,total,money,refund,payment')->where('user_id', $this->request->user_id)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['goodslist'] = (new IntergralOrdergoods())->field('title,images,num,intergral')->where('orderid', $lists['id'])->select();
            foreach ($lists['goodslist'] as $goods) {
                $goods['images'] = json_decode($goods['images'], true);
            }
            if ($lists['status'] == 0) {
                $lists['status_text'] = '待付款';
            }
            if ($lists['status'] == 1) {
                $lists['status_text'] = '待发货';
            }
            if ($lists['status'] == 2) {
                $lists['status_text'] = '待确认';
            }
            if ($lists['status'] == 3) {
                $lists['status_text'] = '已完成';
            }
            if ($lists['status'] == 4) {
                $lists['status_text'] = '已取消';
            }
            if ($lists['refund'] == 2 && $lists['money'] > 0) {
                $lists['status_text'] = $lists['status_text'] . '[退款中]';
            }
            if ($lists['refund'] == 3 && $lists['payment'] == 1) {
                $lists['status_text'] = $lists['status_text'] . '[已退款]';
            }
        }
        $this->result($list, 0, '获取成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $lists = (new IntergralOrder())->where('id', $id)->field('id,status,created,total,province,city,area,street,info,postalname,postalcode,address,refund,money,payment')
            ->where('user_id', $this->request->user_id)->find();
        if (!empty($lists)) {
            $lists['province_text'] = (new Region())->where(['area_code' => $lists['province']])->value('name');
            $lists['city_text'] = (new Region())->where(['area_code' => $lists['city']])->value('name');
            $lists['area_text'] = (new Region())->where(['area_code' => $lists['area']])->value('name');
            $lists['street_text'] = (new Region())->where(['id' => $lists['street']])->value('name');
            $lists['goodslist'] = (new IntergralOrdergoods())->field('title,images,num,intergral')->where('orderid', $lists['id'])->select();
            foreach ($lists['goodslist'] as $goods) {
                $goods['images'] = json_decode($goods['images'], true);
            }
            $lists['ordersn'] = $lists['id'] + pow(21, 8);
            if ($lists['status'] == 1) {
                $lists['status_text'] = '待发货';
            }
            if ($lists['status'] == 2) {
                $lists['status_text'] = '待确认';
            }
            if ($lists['status'] == 3) {
                $lists['status_text'] = '已完成';
            }
            if ($lists['status'] == 4) {
                $lists['status_text'] = '已取消';
            }
            if ($lists['refund'] == 2 && $lists['money'] > 0) {
                $lists['status_text'] = $lists['status_text'] . '[退款中]';
            }
            if ($lists['refund'] == 3 && $lists['payment'] == 1) {
                $lists['status_text'] = $lists['status_text'] . '[已退款]';
            }
        }
        $this->result($lists, 0, '获取成功');
    }

    public function cacelconfirm()
    {
        $data = $this->request->get();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:1,2,3'
        ], [
            'id.require' => '订单id不能为空',
            'status.require' => '修改状态不能为空',
            'status.in' => '修改类型不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new IntergralOrder())->where(['id' => $data['id'], 'user_id' => $this->request->user_id])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '1':
                if ($order['status'] != 0 && $order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单不可取消');
                }
                $status = 4;
                $refund = 2;
                if ($order['money'] == 0 || $order['payment'] == 0) {
                    $refund = 3;
                }
                break;
            case '2':
                if ($order['status'] != 2) {
                    $this->result([], 1, '订单不可完成');
                }
                $status = 3;
                $refund = 1;
                break;
            case '3':
                if ($order['status'] != 0) {
                    $this->result([], 1, '订单状态不可支付');
                }
                if ($order['money'] == 0) {
                    $res = (new IntergralOrder())->where(['id' => $data['id'], 'status' => $order['status']])->update(['status' => 1]);
                    if ($res) {
                        $this->result([], 0, '支付成功');
                    }
                }
                //支付订单 返回微信信息
                $paymentid = repayorder(new Payment());
                $user = $this->request->user;
                $wechatarr = [
                    'pay_title' => '积分订单支付',
                    'payment_id' =>  $paymentid,
                    'money' => $order['money'],
                    'ip' => $this->request->ip(),
                    'user_id' => $this->request->user_id,
                    'params' => json_encode(['trade_type' => 'JSAPI', 'openid' => $user['openid']], true)
                ];
                $parmes = [
                    'openid' => $user['openid'],
                    'user_id' => $user['id']
                ];
                $payment = $this->request->get('payment/d', 2);
                if (empty($payment) || $payment == 2) {
                    $wxres = (new Wechat())->pay($wechatarr);
                    if ($wxres['status'] == true) {
                        //存储支付订单记录
                        $res = (new Payment())->save(['user_id' => $this->request->user_id,'money' => $order['money'], 'type' => 3, 'status' => 1, 'paymentid' => $paymentid, 'ordersn' => $order['id'], 'parmes' => json_encode($parmes, true), 'user_id' => $user['openid']]);
                        if ($res) {
                            $this->result($wxres, 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    }
                } elseif ($payment == 3) {
                    $list = (new Douyin())->pay($wechatarr);
                    if ($list['status'] == true) {
                        //存储支付订单记录
                        $res = (new Payment())->save(['user_id' => $this->request->user_id,'paytype' => 2, 'money' => $order['money'], 'type' => 3, 'status' => 1, 'paymentid' => $paymentid, 'ordersn' => $order['id'], 'parmes' => json_encode($parmes, true), 'user_id' => $user['openid']]);
                        if ($res) {
                            $this->result($list, 0, '获取成功');
                        } else {
                            $this->result([], 1, '获取失败,请重试');
                        }
                    } else {
                        $this->result([], 1, $list['msg'] ?? '获取失败');
                    }
                }

                $this->result([], 1, $res['msg'] ?? '获取失败');
                break;
            default:
                $this->result([], 1, '订单状态错误');
                break;
        }
        $user = (new Users())->where('id', $this->request->user_id)->find();
        Db::startTrans();
        try {
            (new IntergralOrder())->where(['id' => $data['id'], 'status' => $order['status']])->update(['status' => $status, 'refund' => $refund]);
            if ($status == 4) {
                (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 3, $order['id'], '兑换商品取消');
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '操作失败');
        }
        $this->result([], 0, '操作成功');
    }
}
